﻿using CoreShop.Library;
using Sunny.UI;
using System.IO.Ports;
using System.Threading;
using System;
using System.Windows.Forms;
using SqlSugar.Extensions;
using System.Linq;
using CoreShop.Services;
using System.Drawing;
using static CoreShop.Services.PosRemoteServices;
using System.Data;
using Org.BouncyCastle.Ocsp;
using Sunny.UI.Win32;
using NPOI.SS.Formula.Functions;
using static System.Windows.Forms.AxHost;
using System.Threading.Tasks;
using CoreShop.App.Scale;
using CoreShop.Model;
using System.Reflection.Emit;
using System.Diagnostics;

namespace CoreShop.App
{
    public partial class FMainWin : UIAsideMainFrame
    {
        public FMainWin()
        {
            InitializeComponent();
            this.Aside.Visible = false;
            this.comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            // 设置合理的超时时间
            this.comport.ReadTimeout = 500;
            this.comport.WriteTimeout = 500;
            this.ShowTitle = !AppConstVars.showFullScreen;
            this.ShowFullScreen = AppConstVars.showFullScreen;
            //设置关联
            Aside.TabControl = MainTabControl;
            if (Program.frmOrdering == null)
            {
                Program.frmOrdering = new FOrdering();
            }

            if (Program.frmMainPage == null)
            {
                Program.frmMainPage = new frmMainPage();
            }

            if (Program.frmDataMonitor == null)
            {
                Program.frmDataMonitor = new fpgDataMonitor();
            }

            ProcessUtil.GetSystemPara();
            SetupScalePara();
            ProcessUtil.GetClassData(AppConstVars.sysUser.id);

            //增加页面到Main
            AddPage(Program.frmOrdering, (int)GlobalEnumVars.MainWinPageIndex.Page1003);
            AddPage(new FNavigation(), (int)GlobalEnumVars.MainWinPageIndex.Page1001);
            AddPage(Program.frmDataMonitor, (int)GlobalEnumVars.MainWinPageIndex.Page1004);

            //设置Header节点索引            
            Aside.CreateNode("下单", (int)GlobalEnumVars.MainWinPageIndex.Page1003);
            Aside.CreateNode("首页", (int)GlobalEnumVars.MainWinPageIndex.Page1001);
            Aside.CreateNode("数据", (int)GlobalEnumVars.MainWinPageIndex.Page1004);

            //显示默认界面
            Aside.SelectFirst();
        }

        private void FMainWin_Load(object sender, System.EventArgs e)
        {
            string sShortcutName = Security.Decrypt(IniFiles.ReadIniData("Local", "SysName").ObjToString());
            this.Text = sShortcutName + "前台";
            Program.frmOrdering.BindOrderingMaster(0);
            //Program.frmMainWin.ShowOrdering(0);        
        }


        #region 电子秤相关

        DingjianClass.SensorInfo sendorinfo;
        DingjianClass.IS1Info is1Info;
        public ScaleReturnModel scaleModel = null;

        public SerialPort comport = new SerialPort();
        //修改行数量实时变化
        public delegate void SetWeighQty(decimal dQty);
        public event SetWeighQty setWeighQty;
        string InputData = String.Empty;
        public ManualResetEvent _dataReceivedEvent = new ManualResetEvent(true);

        public void SetClearScale()
        {
            if (AppConstVars.mScaleType == 0) return;
            if (AppConstVars.mScaleType == (int)GlobalEnumVars.ScaleType.DJ_OS2_Dll) return;
            if (setWeighQty != null)
            {
                setWeighQty = null;
                if ((comport != null) && (comport.IsOpen))
                {
                    comport.DiscardOutBuffer();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="status">"F"溢出，"S"稳定，"U"不称定</param>
        public void DisplayIS1Info(string status, string sign, string Weight, string fUnit, int flag)
        {
            try
            {            
                string fstatus, fweight;
                fstatus = status;
                scaleModel.status = fstatus == "S" ? true : false;
                //scaleModel.OnLine = fstatus == "U" ? true : false;
                if (AppConstVars.mReadType == 0) scaleModel.status = true;//实时读取数量
                scaleModel.OnLine = true;
                fweight = sign;
                fweight = fweight + Weight;
                scaleModel.Weight = CommFunc.ConvertToDecimal(fweight);
                if (AppConstVars.mConvert == 2)
                    pnlScaleQty.Text = scaleModel.Weight.ToString() + "公斤";
                else
                    AppConstVars.mConvert = 1;
                this.lblScaleQty.Text = (scaleModel.Weight * AppConstVars.mConvert).ToString();
                this.lblScaleQty.Tag = scaleModel.status.ToString();
                if (Program.frmOrdering != null) Program.frmOrdering.GetComportState();
                A_SetLog("=>" + fweight + "\n");
            }
            catch(Exception ex)
            {
                A_SetLog("DisplayIS1Info=>" + ex.Message + "\n");
            }
        }

        /// <summary>设置秤重仪参数
        /// 商品分类
        /// </summary>
        /// <param name="iType"></param>
        private void SetupScalePara()
        {
            if (AppConstVars.mScaleType == (int)GlobalEnumVars.ScaleType.None) return;
            if (AppConstVars.mScaleType == (int)GlobalEnumVars.ScaleType.DJ_OS2_Dll)
            {
                scaleModel = new ScaleReturnModel();
                is1Info = DisplayIS1Info;
                DingjianClass.__SetCallBackFunc("IS1INFO", is1Info);
                int mBaudRate = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "BaudRate"));
                if (mBaudRate < 4800) mBaudRate = 9600;
                string sPortName = CommFunc.ConvertToString(IniFiles.ReadIniData("Weight", "ComPort"));
                bool ret = DingjianClass.__Open(sPortName, mBaudRate);
                if (ret) ShowInfoTip("电子秤打开成功");
            }
            else
                SetupScaleParaByPort();
        }

        /// <summary>
        /// 接口连接的
        /// </summary>
        private void SetupScaleParaByPort()
        {
            try
            {
                if (this.comport.IsOpen) return;
                if (this.comport.IsOpen) this.comport.Close();
                else
                {
                    try
                    {
                        int mBaudRate = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "BaudRate"));
                        if (mBaudRate < 4800) mBaudRate = 9600;
                        this.comport.BaudRate = mBaudRate;
                        this.comport.DataBits = 8;
                        this.comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
                        this.comport.Parity = (Parity)Enum.Parse(typeof(Parity), "None");
                        this.comport.PortName = CommFunc.ConvertToString(IniFiles.ReadIniData("Weight", "ComPort"));

                        // Open the port
                        if (!this.comport.IsOpen)
                        {
                            this.comport.Open();
                            this.comport.DiscardOutBuffer();
                            ShowInfoTip("电子秤打开成功");
                        }
                    }
                    catch (Exception ex1)
                    {
                        this.comport.Close();
                        UIMessageBox.Show("this.comport.Close()", "提示：");
                        Thread thread = new Thread(A_AutoOpenPort);///线程运行
                        thread.IsBackground = true;
                        thread.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "提示：错误代码：4002");
                return;
            }
            if (Program.frmOrdering != null) Program.frmOrdering.GetComportState();
            //设置连接参数
        }

        /// <summary>
        /// 监控COM电子称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //string data = this.comport.ReadExisting();
            //SetPortText(data);

            try
            {
                // 标记事件处理开始
                _dataReceivedEvent.Reset();

                // 快速处理数据，避免耗时操作
                if (comport.IsOpen)
                {
                    string data = this.comport.ReadExisting();
                    SetPortText(data);
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                //if (ErrorReceived != null)
                //{
                //    ErrorReceived(this, new SerialErrorEventArgs(ex));
                //}
            }
            finally
            {
                // 标记事件处理结束
                _dataReceivedEvent.Set();
            }
        }

        public void A_SetLog(string msg)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    if ((this.rtb_log.Visible) && (this.Aside.Visible))
                    {
                        if (this.rtb_log.Text.Length > 5000) rtb_log.Text = String.Empty;
                        this.rtb_log.AppendText(msg);
                        this.rtb_log.HideSelection = false;
                    }
                }));
            }
            catch (Exception ex) { }
        }

        /// <summary>
        /// 解释端口数据
        /// </summary>
        /// <param name="data"></param>
        //private void SetPortText(string data)
        //{
        //    A_SetLog(data);
        //    if (setWeighQty != null) setWeighQty(data);
        //}

        private void OpenPort()
        {
            try
            {
                if (this.comport.IsOpen) this.comport.Close();
                else
                {
                    this.comport.Open();
                    UIMessageBox.Show("this.comport.Open()", "提示：");
                    //this.Invoke(new Action(() =>
                    //{
                    //    this.btnOpenPort.Visible = false;
                    //    this.Height = 700;
                    //}));
                }
            }
            catch (Exception ex1)
            {
                this.comport.Close();
                UIMessageBox.Show(ex1.Message, "提示：错误代码：4003");
            }
        }

        private void A_AutoOpenPort()
        {
            Thread.Sleep(5000);
            OpenPort();
        }


        /// <summary>
        /// 顶尖,实时读数据(不启用
        /// </summary>
        /// <param name="data"></param>
        private void SetPortText_DJ_Time(string data)
        {
            try
            {
                InputData += data;
                //A_SetLog(data);
                if (InputData.Length > 16)
                {
                    string sSubStr = InputData.Substring(InputData.Length - 16);
                    A_SetLog("=>" + sSubStr + "\n");
                    int index = sSubStr.IndexOf("kg");
                    int state = sSubStr.IndexOf("S");//稳定后状态
                    if (index > 6)
                    {
                        string sQtyStr = sSubStr.Substring(index - 6, 6);
                        this.Invoke(new Action(() =>
                        {
                            decimal mScaleQty = CommFunc.ConvertToDecimal(sQtyStr);
                            if (AppConstVars.mConvert == 2)
                                pnlScaleQty.Text = mScaleQty.ToString() + "公斤";
                            else
                                AppConstVars.mConvert = 1;
                            this.lblScaleQty.Text = (mScaleQty * AppConstVars.mConvert).ToString();

                            if (state > 0)
                                this.lblScaleQty.Tag = "True";
                            else
                                this.lblScaleQty.Tag = "False";
                        }));

                        InputData = String.Empty;
                    }
                }
                if (InputData.Length > 20) InputData = String.Empty;
            }
            catch (Exception ex)
            {
                A_SetLog(ex.Message);
            }
        }

        /// <summary>
        /// 顶尖
        /// </summary>
        /// <param name="data"></param>
        private void SetPortText_DJ(string data)
        {
            try
            {
                InputData += data;
                string sQtyStr = "";
                string dataOut = InputData.Replace("kg", "$").Trim();
                string[] parts = dataOut.Split('$');
                foreach (string str in parts)
                {
                    int point = str.LastIndexOf(".");
                    if (point > 3)
                    {
                        A_SetLog("=>" + str + "<\n");
                        //sQtyStr = str.Substring(point - 2, 6);
                        sQtyStr = str.Substring(point - 3, 7);
                    }
                }
                if (sQtyStr.Length > 4)
                {
                    this.Invoke(new Action(() =>
                    {
                        decimal mScaleQty = CommFunc.ConvertToDecimal(sQtyStr);
                        if (AppConstVars.mConvert == 2)
                            pnlScaleQty.Text = mScaleQty.ToString() + "公斤";
                        else
                            AppConstVars.mConvert = 1;
                        this.lblScaleQty.Text = (mScaleQty * AppConstVars.mConvert).ToString();
                        this.lblScaleQty.Tag = "True";
                    }));

                    InputData = String.Empty;
                }
                if (InputData.Length > 200) InputData = String.Empty;
            }
            catch (Exception ex)
            {
                A_SetLog(ex.Message);
            }
        }

        /// <summary>
        /// 大华
        /// </summary>
        /// <param name="data"></param>
        private void SetPortText_DH(string data)
        {
            try
            {
                InputData += data;
                //A_SetLog(data);
                string str = InputData.Trim().Replace("\n", ",").Trim();
                string[] strArray = str.Split(',');
                if (strArray.Length > 1)
                {
                    int cn = strArray.Length;
                    for (int i = 1; i < cn; i++)
                    {
                        str = strArray[i].Trim().Replace(" ", "");
                        if (str.Length >= 4)
                        {
                            //旧版本的大华协议
                            this.Invoke(new Action(() =>
                            {
                                decimal mScaleQty = CommFunc.ConvertToDecimal(str) / 1000;
                                if (AppConstVars.mConvert == 2)
                                    pnlScaleQty.Text = mScaleQty.ToString() + "公斤";
                                else
                                    AppConstVars.mConvert = 1;
                                this.lblScaleQty.Text = (mScaleQty * AppConstVars.mConvert).ToString();
                            }));
                            InputData = String.Empty;
                        }
                        else
                        {
                            //新版本的大华协议
                            string str1 = strArray[i].Trim().Replace(" ", ",");
                            string[] strArray1 = str1.Split(',');
                            if (strArray1.Length > 5)
                            {
                                this.Invoke(new Action(() =>
                                {
                                    decimal mScaleQty = CommFunc.ConvertToDecimal(strArray1[0]) / 1000;
                                    if (AppConstVars.mConvert == 2)
                                        pnlScaleQty.Text = mScaleQty.ToString() + "公斤";
                                    else
                                        AppConstVars.mConvert = 1;
                                    this.lblScaleQty.Text = (mScaleQty * AppConstVars.mConvert).ToString();
                                }));
                                InputData = String.Empty;
                            }
                        }
                    }
                }
                if (InputData.Length > 50) InputData = String.Empty;
            }
            catch (Exception ex)
            {
                A_SetLog(ex.Message);
            }
        }

        /// <summary>
        /// 解释端口数据
        /// </summary>
        /// <param name="data"></param>
        public void SetPortText(string data)
        {
            //A_SetLog(data);
            switch (AppConstVars.mScaleType)
            {
                case (int)GlobalEnumVars.ScaleType.DaHui_ACS:
                    SetPortText_DH(data);
                    break;//大华
                case (int)GlobalEnumVars.ScaleType.DJ_OS2X:
                    SetPortText_DJ(data);
                    break;//顶尖
                //case (int)GlobalEnumVars.ScaleType.DJ_OS2_Time:
                //    SetPortText_DJ_Time(data);
                //    break;//顶尖
            }
        }

        #endregion

        public void ShowTables(int type)
        {
            Aside.SelectPage((int)GlobalEnumVars.MainWinPageIndex.Page1004);
            SendParamToPage((int)GlobalEnumVars.MainWinPageIndex.Page1004, type);
        }

        public void SetOffClass()
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isClassOff, 0)) return;
            if (AppConstVars.classId == 0)
            {
                UIMessageBox.Show("该收银员未当班，不能交班。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            bool isClassOff = false;
            var frm = new frmClassOff();
            frm.Owner = this;
            if (frm.ShowDialog() == DialogResult.OK) isClassOff = true;
            frm.Dispose();
            if (isClassOff)
            {
                //交班重置沽清数据
                //new corecmsfoodsoldoutServices().RecoverySoldout((int)GlobalEnumVars.SoldoutType.Class, null);
                bool loginFlag = false;
                AppConstVars.classId = 0;
                AppConstVars.classNumber = "";
                var login = new frmLogin();
                if (login.ShowDialog() == DialogResult.OK)
                {
                    loginFlag = true;
                    ProcessUtil.GetClassData(AppConstVars.sysUser.id);
                }
                login.Dispose();
                if (!loginFlag) this.SetMainwinClose();
            }
        }

        public void SetOrderList()
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isOrderList, 0)) return;
            var frm = new frmOrderList(0);
            frm.ShowDialog();
            frm.Dispose();
        }

        public void ShowGoodsList()
        {
            var frm = new frmFoodList();
            frm.ShowDialog();
            frm.Dispose();
        }

        public void ShowMember()
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isMemberList, 0)) return;
            var frm = new FrmUser();
            frm.ShowDialog();
            frm.Dispose();
        }

        public void ShowReports()
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isOrderList, 0)) return;
            ShowStatusForm(100, "程序加载中......", 0);
            var frm = new frmReportPage();
            HideStatusForm();
            frm.ShowDialog();
            frm.Dispose();
        }

        public void ShowNavigation()
        {
            Aside.SelectPage((int)GlobalEnumVars.MainWinPageIndex.Page1001);
        }

        public void ShowOrdering(long teskId, long orderId = 0)
        {
            //Program.frmOrdering.BindOrderingMaster(teskId, orderId);
            Aside.SelectPage((int)GlobalEnumVars.MainWinPageIndex.Page1003);
            SendParamToPage((int)GlobalEnumVars.MainWinPageIndex.Page1003, "传值给页面");
        }

        public bool checkExit(bool isShowMsg)
        {
            try
            {
                if (Program.frmOrdering.orderingDetail != null && Program.frmOrdering.orderingDetail.Count > 0)
                {
                    UIMessageBox.Show("有未结帐的明细，不能退出，请取消单据数据后退出！");
                    return false;
                }
                //if ((isShowMsg) && (SysVar.iClassID > 0))
                //{
                //    DialogResult dr = MessageBox.Show("要交班并退出系统吗？选择：[是]-交班并退出系统，[否]- 不交班并退出系统，[取消]-不退出系统。", "提示：", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                //    if (dr == System.Windows.Forms.DialogResult.Yes)
                //    {
                //        A_setClassTo();
                //    }
                //    else if (dr == System.Windows.Forms.DialogResult.Cancel)
                //    {
                //        return false;
                //    }
                //}
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "错误023"); }
            return true;
        }


        private void FMainWin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkExit(true))
            {
                e.Cancel = true;
                return;
            }
            if (!ShowAskDialog("确认要退出系统吗？")) e.Cancel = true; 
        }

        private void FMainWin_FormClosed(object sender, FormClosedEventArgs e)
        {
            //if ((comport != null) && (comport.IsOpen))
            //{
            //    comport.DiscardInBuffer();
            //    comport.Close();
            //}
        }

        public void SetMainwinClose()
        {
            this.Close();
        }

        public void ShowLog()
        {
            Aside.Visible = true;
            rtb_log.Visible = true;
            pnl_port.Visible = true;
        }

        private void lblScaleQty_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (setWeighQty != null) setWeighQty(CommFunc.ConvertToDecimal(lblScaleQty.Text));
                Program.frmOrdering.lblScaleQty.Text = this.lblScaleQty.Text;
                Program.frmOrdering.lblScaleQty.Tag = this.lblScaleQty.Tag;
            }
            catch (Exception ex) {
                //MessageBox.Show(ex.Message); 
            }
        }

        /// <summary>
        /// 额显窗口
        /// </summary>
        private void CreateCustDisplay()
        {
            int sShowFlag = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "ShowFlag"));
            if ((sShowFlag == 1) && (Screen.AllScreens.Count() >= 1) && (Program.frmCustShow == null))
            {
                //双屏显示
                Program.frmCustShow = new frmCustomerDisplay();
                Program.frmCustShow.Show();
            }
        }

        private void FMainWin_Shown(object sender, EventArgs e)
        {
            CreateCustDisplay();
            //传参数给fpgDataMonitor_ReceiveParams接收，下载数据
            SendParamToPage((int)GlobalEnumVars.MainWinPageIndex.Page1004, 1);
        }

        private void pnlScaleQty_Click(object sender, EventArgs e)
        {
            try
            {
                //Task.Factory.StartNew(() =>
                //{
                //    GsIScaleInterface superwinScale = new SuperwinScale();
                //    ScaleReturnModel str = superwinScale.GetScaleWeight();

                //    UIMessageBox.ShowSuccess(str.Data);
                //});
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowSuccess("错误:" + ex.Message);
            }
        }
    }
}
